import Taro, {Component, Config} from '@tarojs/taro'
import {View, Text, Image, Canvas} from '@tarojs/components'
import NavbarBlock from "../../common/components/navbarBlock";
import classNames from 'classnames'
import wxcharts from "../../common/js/wxcharts";
import './detail.scss'

import bg from '../../common/assets/navbar_bg4@2x.png'
import detailsLine from '../../common/assets/details_line@2x.png'
import detailsBg from '../../common/assets/details_bg@2x.png'
import homeCurrentseasonSel from '../../common/assets/home_Currentseason_sel@2x.png'
import homeNextmonthSel from '../../common/assets/home_nextmonth_sel@2x.png'
import TopBanner from "./components/topBanner";
import {date} from "../../common/js/utils";
import common from "../../common/js/common";
import ajax from "../../net/ajax";
import apiObject from "../../net/api";


interface ComponentState {
    goodsList: Array<any>
    topBannerList: Array<any>
    currentCheck: number
    windowHeight: number
    windowWidth: number
    copyAddress: string,
    details: any,
    level: number,
    lineData: any,
    dates: any,
    isShowHome: number,
    hasVideo: boolean
}

export default class Detail extends Component<{}, ComponentState> {


    config: Config = {
        navigationStyle: 'custom',
        navigationBarTitleText: '详情页',
        enablePullDownRefresh: true,
        onReachBottomDistance: 50,
        backgroundTextStyle: 'dark',
    };

    constructor(props) {
        super(props);
        this.state = {
            topBannerList: [bg, homeCurrentseasonSel, homeNextmonthSel],
            currentCheck: 0,
            windowWidth: 750,
            windowHeight: 400,
            copyAddress: '',
            goodsList: [1, 1, 1, 1, 1],
            details: {},
            level: 1,
            lineData: [],
            dates: [],
            isShowHome: 0,
            hasVideo: false
        };
    }

    onShareAppMessage() {
        let {details} = this.state;
        let backUrl = encodeURIComponent(`/pages/detail/detail?id=${details.id}&isShowHome=${1}`);
        return {
            title: '抱果精选-' + details.name,
            imageUrl: details.skuImg,
            path: `pages/common/commonInSite?backUrl=${backUrl}`,
            success(res) {

            }
        }
    }

    componentWillMount() {
        let id = this.$router.params.id;
        let isShowHome = this.$router.params.isShowHome;
        this.setState({isShowHome: isShowHome?parseInt(isShowHome):0});
        this.fechDetails(id);
        this.fechPrices(id);
        var windowWidths, windowHeights;    //定义宽高
        var res = Taro.getSystemInfoSync();    //试图获取屏幕宽高数据
        windowWidths = 750 / 750 * res.windowWidth;  //以设计图750为主进行比例算换
        windowHeights = res.windowWidth / 750 * 320;    //以设计图750为主进行比例算换
        this.setState({
            windowWidth: windowWidths,
            windowHeight: windowHeights,
            level: common.getLevel()
        })
    }

    fechPrices(id) {
        Taro.showLoading({title: '加载中...'});
        ajax.post(apiObject.skuPrices, {skuId: id}).then(res => {
            if (res.statusCode == 200) {
                let data = res.data;
                let dates = [];
                for (let i = 0; i < data.length; i++) {
                    dates.push(date('d', data[i].date));
                }
                let newdates = this.fenge(dates, 10);
                this.setState({
                    lineData: data,
                    dates: newdates
                }, () => {
                    let newArray = this.fenge(data, 10);
                    this.upDateDataLine(newArray[0]);
                    Taro.hideLoading();
                })
            }
        })
    }

    fenge(arr, N) {
        var result = [];
        for (var i = 0; i < arr.length; i += N) {
            result.push(arr.slice(i, i + N));
        }
        return result
    }

    fechDetails(id) {
        ajax.post(apiObject.skuDetails, {skuId: id}).then(res => {
            if (res.statusCode == 200) {
                const data = res.data;
                let {headImgs, videoUrl} =  data;
                
                let imgArry = headImgs.split(',');

                let hasVideo = false;
                if(videoUrl){
                    imgArry.splice(0, 0, videoUrl);
                    hasVideo = true;
                }
                this.setState({
                    hasVideo: hasVideo,
                    details: data,
                    topBannerList: imgArry,
                    copyAddress: data.material
                })
            } else {
                //请求异常
                Taro.showToast({
                    title: '请求异常,请重试!',
                    icon: 'none',
                    duration: 2000
                })
            }
        })
    }

    upDateDataLine(lineData) {
        let line = [];
        let dates = [];
        if (lineData) {
            lineData.forEach(function (item) {
                let lineDate = item.date;
                let stepAccount = item.stepAccount;
                line.push(stepAccount);
                dates.push(date('d', lineDate));
            });
        }

        let {windowWidth, windowHeight} = this.state;
        new wxcharts({
            canvasId: 'lineCanvas',
            type: 'line',
            animation: true,  //是否开启动画
            categories: dates,
            series: [{
                name: '',
                data: line,
                format: function (val) {
                    return val.toFixed(2) + '分';
                }
            }],
            xAxis: {   //是否隐藏x轴分割线
                disableGrid: false,
            },
            yAxis: {
                title: '',
                format: function (val) {
                    return val.toFixed(0);
                },
            },
            width: windowWidth, //图表展示内容宽度
            height: windowHeight, //图表展示内容高度
            dataLabel: false,    //是否在图表上直接显示数据
            dataPointShape: true, //是否在图标上显示数据点标志
            extra: {
                lineStyle: 'curve'  //曲线
            },
        });
    }


    onBackClick() {
        let pages = Taro.getCurrentPages();
        if (pages.length > 1) {
            Taro.navigateBack()
        } else {
            Taro.switchTab({url: '/pages/index/index'})
        }
    }

    onPullDownRefresh() {
        let id = this.$router.params.id;
        this.fechDetails(id);
        this.fechPrices(id);
        Taro.stopPullDownRefresh();
    }

    onTabCheckClick(position) {
        let {lineData} = this.state;
        let newArray = this.fenge(lineData, 10);
        this.upDateDataLine(newArray[position]);
        this.setState({
            currentCheck: position
        })
    }

    onDownLoadClick() {
        let {copyAddress} = this.state;
        Taro.setClipboardData({
            data: copyAddress,
            success(res) {
                Taro.showToast({
                    title: "复制成功"
                })
            }
        })
    }

    render() {
        let {topBannerList, currentCheck, isShowHome,  details, level, dates, hasVideo} = this.state;
        return (
            <View className='detail-container'>
                <NavbarBlock
                    isShowBack={true}
                    isShowHome={isShowHome}
                    onBackClick={this.onBackClick.bind(this)}
                    title={'详情页'}>
                    <TopBanner topBannerList={topBannerList} showVideo={hasVideo}/>
                    <View className='introduce-content'>
                        <View className='title-content'>
                            <Text className='title'>{details.name}</Text>
                            <Text className='code'>{details.spac}</Text>
                        </View>
                        <View className='des-content'>
                            <Text className='price-title'>供货价</Text>
                            {level === 0 && <Text
                                className='price'>¥{details.sourcePrice > 0 ? parseFloat((details.sourcePrice / 100).toFixed(2)) : '***'}</Text>}
                            {level === 1 && <Text
                                className='price'>¥{details.firstSourcePrice > 0 ? parseFloat((details.firstSourcePrice / 100).toFixed(2)) : details.firstSourcePrice}</Text>}
                            {level === 2 && <Text
                                className='price'>¥{details.secondSourcePrice > 0 ? parseFloat((details.secondSourcePrice / 100).toFixed(2)) : details.secondSourcePrice}</Text>}
                            {level === 3 && <Text
                                className='price'>¥{details.thridSourcePrice > 0 ? parseFloat((details.thridSourcePrice / 100).toFixed(2)) : details.thridSourcePrice}</Text>}
                            {level === 4 && <Text
                                className='price'>¥{details.sourcePrice > 0 ? parseFloat((details.sourcePrice / 100).toFixed(2)) : details.sourcePrice}</Text>}

                            {/* <Text className='price'>¥{details }</Text> */}
                            <Text className='price-title'>建议售价</Text>
                            {level === 0 && <Text
                                className='price'>¥{details.salePrice > 0 ? parseFloat((details.salePrice / 100).toFixed(2)) : '***'}</Text>}
                            {level === 1 && <Text
                                className='price'>¥{details.firstSalePrice > 0 ? parseFloat((details.firstSalePrice / 100).toFixed(2)) : details.firstSalePrice}</Text>}
                            {level === 2 && <Text
                                className='price'>¥{details.secondSalePrice > 0 ? parseFloat((details.secondSalePrice / 100).toFixed(2)) : details.secondSalePrice}</Text>}
                            {level === 3 && <Text
                                className='price'>¥{details.thridSalePrice > 0 ? parseFloat((details.thridSalePrice / 100).toFixed(2)) : details.thridSalePrice}</Text>}
                            {level === 4 && <Text
                                className='price'>¥{details.salePrice > 0 ? parseFloat((details.salePrice / 100).toFixed(2)) : details.salePrice}</Text>}
                            {/* <Text className='price'>¥299</Text> */}
                        </View>
                        <Image className='right-bg' mode='widthFix' src={detailsBg}/>
                    </View>

                    <View className='chart-content'>
                        <View className='title-content'>
                            <Image className='icon' mode='widthFix' src={detailsLine}/>
                            <Text className='title'>历史供货价走势图</Text>
                        </View>
                        <View className='tab-content'>
                         <Text onClick={this.onTabCheckClick.bind(this, 0)}
                                                  className={classNames('item-default', currentCheck == 0 && 'item-check')}>{dates[0][0]}号-{dates[0][dates[0].length - 1]}号</Text>

                            <Text onClick={this.onTabCheckClick.bind(this, 1)}
                                                  className={classNames('item-default', currentCheck == 1 && 'item-check')}>{dates[1][0]}号-{dates[1][dates[1].length - 1]}号</Text>

                            <Text onClick={this.onTabCheckClick.bind(this, 2)}
                                   className={classNames('item-default', currentCheck == 2 && 'item-check')}>{dates[2][0]}号-{dates[2][dates[2].length - 1]}号</Text>
                        </View>
                        <Canvas
                            className='chart-info__canvas'
                            canvasId='lineCanvas'
                        />
                    </View>
                    <View className='goods-content'>
                        <View className='title-content'>
                            <Image className='icon' mode='widthFix' src={detailsLine}/>
                            <Text className='title'>物料清单</Text>
                        </View>
                        <View className='action-content'>
                            <Text className='point'>*</Text>
                            <Text className='action-title'>下载物料为zip格式压缩包</Text>
                            {level > 0 && <Text className='btn' onClick={this.onDownLoadClick.bind(this)}>复制物料地址</Text>}
                        </View>
                        {/*{goodsList && goodsList.map((item, index) => (*/}
                        {/*    <View className='goods-list' key={'goodsList'+index}>*/}
                        {/*        <Text className='goods-title'>文件名: 车厘子海报物料</Text>*/}
                        {/*        <Text className='goods-des'>128M</Text>*/}
                        {/*    </View>*/}
                        {/*))}*/}
                        {/*{goodsList && <View className='goods-list-x'/>}*/}
                    </View>
                </NavbarBlock>
            </View>
        )
    }
}
